import React, {useState, useEffect} from 'react';
import { Select, message } from 'antd';
import { OrgTypeItem } from '../data.d';
import { getFirstLevelOrgId } from '../service';

interface OrgTypeProps {
  init:true;
  defaultvalue:string;
  disabled:boolean;
  selectChange: (values:any) => void;
}

const { Option } = Select;
/**
 * 
 * 所属机构控件
 */
const FirstOrgListComponent: React.FC<OrgTypeProps> = (props) => {

  const { init, defaultvalue,disabled,selectChange } = props;
  const [types, setTypes] = useState([]);

  const getList = () =>{
    new Promise((resolve, reject) => {
      getFirstLevelOrgId()
        .then((res) => {
          if (res && res.code === 200) {
            setTypes(res.data);
            resolve(true);
          } else {
            message.error('请求失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  }
  useEffect(() => {
    if(init){
      getList();
    }
  },[init]);

  return (
      <Select
        showSearch
        placeholder="请选择所属机构"
        optionFilterProp="children"
        defaultValue={defaultvalue}
        disabled={disabled}
        allowClear
        style={{ width: 200 }}
        onChange={(values) =>selectChange(values)}
        onFocus={() => getList()}
      >
        {types.map((item:OrgTypeItem) => <Option key={item.topOrgId} value={item.topOrgId}>{item.orgName}</Option>)}
    </Select>
  );
};

export default FirstOrgListComponent;
